package com.m3958.firstgwt.server.servlet;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.WebContextFMCfg;
import com.m3958.firstgwt.server.session.SessionUser;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@Singleton
public class StaticFileServlet  extends HttpServlet {
		  /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private WebContextFMCfg fmCfg;
	
	@Inject
	private AppUtilService autils;
	
	@Inject
	private Injector injector;
	

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) 
	                               throws ServletException, IOException {
		String uri = req.getRequestURI();
		if("/".equals(uri)){
			uri = "/in";
		}
		if("/in".equals(uri) || "/FirstGwt.html".equals(uri)){
			SessionUser su = injector.getInstance(SessionUser.class);
			boolean inDebug = req.getRequestURL().toString().contains("127.0.0");
			if(!su.isLogined()){
				if(inDebug){
					res.sendRedirect("/login.html#next=sitebuilder&debug=true");
				}else{
					res.sendRedirect("http://lgb.m3958.com/login.html#next=sitebuilder");
				}
				return;
			}
			if(inDebug){
				sendTpl(req, res,"FirstGwt.ftl");
			}else{
//				RequestScopeObjectService rso = injector.getInstance(RequestScopeObjectService.class);
//				if(!"lgb.fh258.com".equals(rso.getRequestWebHost().getName())){
//					res.sendRedirect("http://lgb.fh258.com/in");
//					return;
//				}
				sendTpl(req, res,"FirstGwt.ftl");
			}
			return;
		}
		
	    // Get the file to view
	    String file = req.getPathTranslated();
	    File f = new File(file);
	    
	    // No file, nothing to view
//	    if (!f.isFile()) {
//	    	RequestDispatcher rd = req.getRequestDispatcher("/webfront");
//	    	req.setAttribute("origin_ruri", req.getRequestURI());
//	    	rd.forward(req, res);
//	    	return;
//	    }
	    autils.sendSiteFile(req,res,f,getServletContext().getMimeType(f.getAbsolutePath()));
	  }
	
	private void sendTpl(HttpServletRequest req, HttpServletResponse res,String fn){
		res.setContentType("text/html;charset=UTF-8");   
		res.setCharacterEncoding("UTF-8");
		try {
			doSendTpl(req, res, fn);
		} catch (IOException e) {
			if(e instanceof FileNotFoundException){
				try {
					doSendTpl(req, res, "FirstGwt.html");
				} catch (IOException e1) {
					e1.printStackTrace();
				} catch (TemplateException e1) {
					e1.printStackTrace();
				}
			}else{
				e.printStackTrace();
			}
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
	
	private void doSendTpl(HttpServletRequest req, HttpServletResponse res,String fn) throws IOException, TemplateException{
		Map<String,Object> rootDataModel = new HashMap<String, Object>();
		rootDataModel.put("siteId", req.getParameter("siteId"));
		rootDataModel.put("inittoken", req.getParameter("inittoken"));
		Template template = fmCfg.getTemplate(fn);
		Writer writer = res.getWriter();
		template.process(rootDataModel, writer);
		writer.flush();
	}
}
